package com.guanghua.brick.html.ajax;

import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.guanghua.brick.util.XmlUtil;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.Result;

public class AJAXXmlFileResult implements Result {
	
	private static final Log logger = LogFactory.getLog(AJAXXmlFileResult.class);
	
	public void execute(ActionInvocation action) throws Exception {
		//读取annotation
		String m = action.getProxy().getMethod();
		m = (m!=null)?m:"execute";
		Method method = action.getAction().getClass().getMethod(m, (Class[])null);

		AJAXResult a = null;
		if (method != null) a = (AJAXResult)method.getAnnotation(AJAXResult.class);
		String value = a.value();

		//读取数据
		Object o = ServletActionContext.getRequest().getAttribute(value);
		
		
		//按照xml格式序列化
		String xml = "";
		if (o != null) {
			//结果是string
			if (a.result() == AJAXResultType.STRING) {
				xml = XmlUtil.stringToXml(o.toString());
			//结果是array
			} else if (a.result() == AJAXResultType.ARRAY) {
				if (o instanceof String[]) {
					xml = XmlUtil.stringArrayToXml((String[])o);
				} else if (o instanceof List) {	
					xml = XmlUtil.stringListToXml((List)o);
				} else {
					xml = XmlUtil.stringArrayToXml(new String[]{o.toString()});
				}
			//结果是Object
			} else if (a.result() == AJAXResultType.OBJECT) {
				if (o instanceof Map[]) {
					xml = XmlUtil.mapArrayToXml((Map[])o);
				} else if (o instanceof Map) {
					xml = XmlUtil.mapToXml((Map)o);
				} else if (o instanceof List) {
					xml = XmlUtil.mapListToXml((List)o);
				}
			} else {
				//错误
				logger.error("not the expected xml result type");
			}
		} else {
			//错误
			logger.error("data to transfer xml is null");
		}
		
		//输出xml文件
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/xml");    
		response.setHeader("Cache-Control", "no-cache");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.print(xml);
		out.flush();
		out.close();
	}

}
